package com.wangyadong.hobby.nio.charter1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class PlainNio2EchoServer {

    public void server(int port) throws IOException {
        System.out.println(" Listing for connections on port " + port);
        AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();
        serverChannel.bind(new InetSocketAddress(port));
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel channel, Object attachment) {
                serverChannel.accept(null, this);
                ByteBuffer allocate = ByteBuffer.allocate(100);
                channel.read(allocate, allocate, new EchoCompletionHandler(channel));
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                try {
                    serverChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    public static void main(String[] args) {
        int OP_WRITE = 1 << 2;
        int OP_READ = 1 << 0;
        System.out.println("==");
    }
}
